﻿using System;
using System.Windows.Forms;
using TimeTable.Domain.DataAccess;
using TimeTable.Domain.Entity;

namespace TimeTable.AddForms
{
    public partial class NewDivisionForm : Form
    {
        private readonly DivisionType _type;

        public NewDivisionForm(DivisionType type)
        {
            InitializeComponent();

            _type = type;

            switch (type)
            {
                case DivisionType.University:
                {
                    Text = "New university";
                    parentLabel.Visible = false;
                    parent.Visible = false;
                    break;
                }
                case DivisionType.Faculty:
                {
                    Text = "New faculty";
                    parent.DataSource = DataAccessConnection.Instance.GetDivisionsByType(DivisionType.University);
                    break;
                }
                case DivisionType.Chair:
                {
                    Text = "New chair";
                    parent.DataSource = DataAccessConnection.Instance.GetDivisionsByType(DivisionType.Faculty);
                    break;
                }
            }

            head.DataSource = DataAccessConnection.Instance.GetAllTeachers();
        }

        private void CancelButtonClick(object sender, EventArgs e)
        {
            Close();
        }

        private void OKButtonClick(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(name.Text)) throw new Exception("Name can not be empty!");

                var teacher = head.SelectedItem as Teacher;
                if (teacher == null) throw new Exception("Please select head!");

                var division = new Division
                {
                    Name = name.Text,
                    Head = teacher.ID,
                    Type = _type
                };

                if (_type != DivisionType.University)
                {
                    var divis = parent.SelectedItem as Division;
                    if (divis == null) throw new Exception("Please select parent division!");

                    division.Parent = divis;
                }

                if (DataAccessConnection.Instance.DivisionExists(division))
                {
                    MessageBox.Show("Division already exists!");
                }
                else
                {
                    DataAccessConnection.Instance.AddDivision(division);

                    MessageBox.Show("Division successfully added!");

                    Close();
                }
            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.Message, "Error");
            }
        }
    }
}
